const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');

const app = new Koa();
const router = new Router();

// 使用bodyParser中间件解析请求体
app.use(bodyParser());

// 定义路由
router.get('/', async (ctx) => {
  ctx.body = 'Welcome to the home page!';
});

router.get('/about', async (ctx) => {
  ctx.body = 'This is the about page.';
});

router.post('/submit', async (ctx) => {
  const { name, age } = ctx.request.body;
  if (!name || !age) {
    throw new Error('Invalid input: name and age are required.');
  }
  ctx.body = `Received data: { name: "${name}", age: ${age} }`;
});

router.get('/error', async (ctx) => {
  throw new Error('Something went wrong!');
});

router.get('/not-found', async (ctx) => {
  ctx.status = 404;
  ctx.body = 'This page does not exist.';
});

// 全局错误处理中间件
app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.status = err.status || 500;
    ctx.body = {
      error: {
        message: err.message,
        status: ctx.status,
        stack: app.env === 'development' ? err.stack : undefined
      }
    };
    ctx.app.emit('error', err, ctx); // 触发错误事件，便于日志记录等
  }
});

// 使用路由中间件
app.use(router.routes()).use(router.allowedMethods());

// 监听错误事件
app.on('error', (err, ctx) => {
  console.error('Server error:', err);
  if (ctx) {
    console.error('Request URL:', ctx.url);
  }
});

app.listen(3000, () => {
  console.log('Server is running at http://localhost:3000');
});